<html>

<head>

<title>Dreambox</title>
 
<link rel="stylesheet" href="jquery.mobile-1.0a4.1.min.css" />
<script src="jquery-1.5.2.min.js"></script>
<script src="domgen.js"></script>
<script src="jquery.mobile-1.0a4.1.min.js"></script>
<script src="json2.js"></script>
<script src="osami_fin.js"></script>
<style>
#volume_canvas{
	padding-bottom : 5pt;
	margin-left : 5pt;
}

</style>

<script type="text/javascript">


function addChannel(channelid, title, description){
	var rootelem = $("#channels_list");


	Settings.channels[channelid] = {channelid : channelid, title : title, description : description};
	Settings.channelOrder.push( channelid );

	var program_spec = [
		'li',
		{
			"id" : "channel_" + channelid
		},

		[
			'a',
			{
				"class" : "ui-link",
				//"href" : "#programs_page"
				
				_onclick : function() {
					//document.location.href = "#programs_page";
					OSAMI.postAndroidIntent({
						action : OSAMI.HID_QUERY,
						extras : {
							"query"    : "org/osami/PROGRAMS",
							"deviceID" : "tvbox",
							"channel"  : channelid
						}
					});
					$("#channel-header").find("h1").text(title);

					$.mobile.changePage("programs_page");
				}
			},
			[
				'h3',
				{
				
					"_innerText" : title
				},
				'p',
				{
					"_innerText" : description
				}

			],
			'a',
			{
				"data-rel" : "dialog",
				"data-transition" : "slideup",
				_onclick : function(){
					setChannel(channelid);
					console.log(this)
					$(this).removeClass("ui-btn-active");
					console.log(this)
				}
			}
		]
	];

	domgen.generate(rootelem[0], program_spec, { clean : false });

	rootelem.listview("refresh");
}


function addProgram(progid, title, description, start, end)
{
	var rootelem = $("#programs_list");
/*
	<li><a href="index.html"> 
				<img src="images/album-bb.jpg" /> 
				<h3>Broken Bells</h3> 
				<p>Broken Bells</p> 
				</a><a href="lists-split-purchase.html" data-rel="dialog" data-transition="slideup">Purchase album
			</a></li> 
			*/
	var program_spec = [
		'li',
		{
			"id" : "program_" + progid
		},
 
		[ 
			
			'a',
			{
				// TODO: Show info about program?
			},
			[
				'h3',
				{
					"_innerText" : title
				},
				'p',
				{
					"_innerText" : description
				}
			],
			'a',
			{
				"data-rel" : "dialog",
				"data-transition" : "slideup"
			}		
		]
	];

	domgen.generate(rootelem[0], program_spec, { clean : false });

	rootelem.listview("refresh");
}

// The mousemove event handler.
var started = true;
var contex = null;
var canvas = null;

// http://stackoverflow.com/questions/1255512/how-to-draw-a-rounded-rectangle-on-html-canvas
CanvasRenderingContext2D.prototype.roundRect = function(sx,sy,ex,ey,r) {
    var r2d = Math.PI/180;
    if( ( ex - sx ) - ( 2 * r ) < 0 ) { r = ( ( ex - sx ) / 2 ); } //ensure that the radius isn't too large for x
    if( ( ey - sy ) - ( 2 * r ) < 0 ) { r = ( ( ey - sy ) / 2 ); } //ensure that the radius isn't too large for y
    this.beginPath();
    this.moveTo(sx+r,sy);
    this.lineTo(ex-r,sy);
    this.arc(ex-r,sy+r,r,r2d*270,r2d*360,false);
    this.lineTo(ex,ey-r);
    this.arc(ex-r,ey-r,r,r2d*0,r2d*90,false);
    this.lineTo(sx+r,ey);
    this.arc(sx+r,ey-r,r,r2d*90,r2d*180,false);
    this.lineTo(sx,sy+r);
    this.arc(sx+r,sy+r,r,r2d*180,r2d*270,false);
    this.closePath();
}

CanvasRenderingContext2D.prototype.triangle = function(left, top, right) {
	this.beginPath();
    this.moveTo(left[0], left[1]);
    this.lineTo(top[0], top[1]);
    this.lineTo(right[0], right[1]);
    this.lineTo(left[0], left[1]);
    this.closePath();
    
}

function drawVolumeBackground(context)
{
	context.fillStyle = "white";
	context.fillRect (0, 0, canvas.width, canvas.height );
}

function finalizeVolumeBar(context){
	/*
	context.fillStyle = "white";
	context.roundRect (0, 0, canvas.width, canvas.height, 10 );
	context.clip();
	*/
}

var Settings = {
	mute : false,
	previous_volume : -1,
	change_volume_request_counter : 0,

	/// ID of the current channel
	current_channel : "",

	/// Maps channel id to channel object
	channels : {},
	/// Order of the channels on the list. ID's only
	channelOrder : []
}

function setChannel(channelid)
{
	console.log("setchan:" + channelid)
	$("#current-channel").text(Settings.channels[channelid].title)

	Settings.current_channel = channelid;

	OSAMI.postAndroidIntent({
		action : OSAMI.HID_QUERY,
		extras : {
			"query"     : "org/osami/SET_CHANNEL",
			"channelid" : channelid, 
			"deviceID"  : "tvbox"
		}
	});
}

function jumpChannel(amount){
	
	if(Settings.channelOrder.length == 0 || amount >= Settings.channelOrder.length){
		return;
	}

	var i = Settings.channelOrder.indexOf(Settings.current_channel);
	i += amount
 	i = (Settings.channelOrder.length + i) % Settings.channelOrder.length;

	setChannel(Settings.channelOrder[i]);
	
}

function channelPrev()
{
	jumpChannel(-1);
}


function channelNext()
{
	jumpChannel(1);
}


function applyVolume(vol){
	OSAMI.postAndroidIntent({
		action : OSAMI.HID_QUERY,
		extras : {
			"query"    : "org/osami/SET_VOLUME",
			"volume"   : vol, // 0-100
			"deviceID" : "tvbox"
		}
	});
}

function ev_mousemove (ev) {
	var x, y;

	// Get the mouse position relative to the canvas element.
	if (ev.layerX || ev.layerX == 0) { // Firefox
		x = ev.layerX;
		y = ev.layerY;
	} else if (ev.offsetX || ev.offsetX == 0) { // Opera
		x = ev.offsetX;
		y = ev.offsetY;
	}

	var volume;
	var integerVolume;

	volume = x / canvas.width;
	volume = Math.min(1.0, volume);
	volume = Math.max(0.0, volume);
	
	integerVolume = parseInt(Math.round(volume * 100));

	if(Settings.previous_volume == integerVolume){
		// No need to update
		return;
	}

	drawVolumeBar(context, volume);
	previous_volume = integerVolume;

	if(Settings.mute){
		return;
	}
	
	Settings.change_volume_request_counter += 1;
	

	// Sends the event to tvbox with delay and only the last change within 250ms
	// No point in bombarding the OSGi system with events.
	setTimeout(function(aRequestID, aVolume){
		return function(){
			if(aRequestID == Settings.change_volume_request_counter){
				// Send request to OSGi
				applyVolume(aVolume);
			}
		}
	}(Settings.change_volume_request_counter, Settings.previous_volume), 250);
	
}

/** Draw new value if changed. Return true if changed, false otherwise */
function drawVolumeBar(context, aVolume)
{
	var aVolume = Math.min(1.0, aVolume);
	aVolume = Math.max(0.0, aVolume);

	volume = parseInt(Math.round(aVolume * 100));
	volume = String(volume) + "%";


	context.globalCompositeOperation = "source-over";
	//context.roundRect (0, 0, canvas.width, canvas.height, 10 );
	

	//context.clip();

	// clear
	drawVolumeBackground(context);
 
	var volume_gradient = context.createLinearGradient(0, 0,  canvas.width, 0);
	volume_gradient.addColorStop(0, "rgb(0,128,0)");
	volume_gradient.addColorStop(1, "rgb(0,255,0)");
	context.fillStyle = volume_gradient;
	context.fillRect(0, 0,  canvas.width * aVolume, canvas.height);

	// Cut triangle out from top
	context.globalCompositeOperation = "destination-out";
	context.triangle([0,canvas.height], [0, 0], [canvas.width,0]);
	context.fill();
  
	context.globalCompositeOperation = "source-over";
	context.fillStyle = "black";
	context.font = "20pt Arial";
	var w = context.measureText(volume).width;

	context.fillText(volume, canvas.width / 2 - w / 2, canvas.height / 2 + 10, canvas.width);
 
 	//context.roundRect (0, 0, canvas.width, canvas.height, 10 );
 	//context.clip();
	finalizeVolumeBar(context);
}

function toggleMute(value)
{
	if(value){
		console.log("TODO: mute");
		Settings.mute = true;
		applyVolume(0);
	}
	else{
		Settings.mute = false;
		console.log("TODO: unmute");
		applyVolume(Settings.previous_volume);
	}
}

function setupApp(){

	canvas = document.getElementById("volume_canvas");
	canvas.width = Math.max(100, window.innerWidth - 20 * 2);
	canvas.height = canvas.width * 0.33 / 2;

	// Mouse handler for testing 
	canvas.addEventListener('mousemove', ev_mousemove, false);
	
	canvas.addEventListener('touchstart', function(ev){ 
		// Reguired to keep touchmove events firing
		// http://code.google.com/p/android/issues/detail?id=5491
		ev.preventDefault();
	}, false);

	canvas.addEventListener('touchmove', function(ev){ 
		ev_mousemove(ev); 
	}, false);

	var ctx = canvas.getContext("2d");
	context = ctx;

	// TODO: Initial values
	//drawChannelSelector(context, 1);
	drawVolumeBar(context, 0.5);

	OSAMI.setupIntentListener(OSAMI.HID_RESPONSE);

	OSAMI.addIntentListener(OSAMI.HID_RESPONSE, function(data){
		var channels = data.extras["channels"];

		// TODO: Volume, current channel

		// Handle channel list updates
		if(channels){
			for( var i in channels )
			{
				channel = channels[i];
				console.log("Channel:"+String(channel));
				addChannel(channel.id, channel.name, channel.showing);
			}
		}

		// Handle program list updates
		var programs = data.extras["programs"];
		if(channels){
			for( var i in programs )
			{
				program = programs[i];
				console.log("Channel:"+String(program));
				addProgram();
			}
		}
	});
}


window.onload = function(){
	try{
		//$.mobile.ajaxEnabled = false;

		console.log("Fetching channels"); 

		setupApp();

		OSAMI.postAndroidIntent({
			action : OSAMI.HID_QUERY,
			extras : {
				"query"    : "org/osami/CHANNELS",
				"deviceID" : "tvbox"
			}
		});
		
		addChannel("channe1l.id", "channel1.name", "channel1.showing");
		addChannel("channel2.id", "channel2.name", "channel2.showing");
		addChannel("channel3.id", "channel3.name", "channel3.showing");
		Settings.current_channel = "channe1l.id";

		addProgram("df", "df", "dkfjkdfj", 3123123, 123123)
	}
	catch(e){
		console.log(String(e));
		throw e;
	}
}

</script>

</head>

<body data-theme="a">
	
	<div data-role="page" id="channels_page">
	
		
		<div data-role="header">
			<h1>OSAMI-FIN Dreambox</h1>
		</div>
		
		<div  data-role="content">
			
			<ul data-role="listview" data-inset="true">
				<li data-role="list-divider">Volume</li>

				<input type="checkbox" name="mute-toggle" id="mute-toggle" onchange="javascript:toggleMute(this.value)" />
				<label for="mute-toggle">Mute</label>

				<canvas id="volume_canvas" width="100" height="100" style="position:relative;"></canvas>
			</ul>
			
			
			<ul data-role="listview" data-inset="true" id="channels_list" data-split-icon="star">
				<li data-role="list-divider">Channels</li>
				
				<li id="current-channel">NOW SHOWS</li> 

				<fieldset class="ui-grid-a">
					<div class="ui-block-a"><button type="submit" data-icon="arrow-l" onclick="javascript:channelPrev();">Prev</button></div>
					<div class="ui-block-b"><button type="submit" data-icon="arrow-r" data-iconpos="right" onclick="javascript:channelNext();">Next</button></div>	
				</fieldset>

				<!-- Generated channels list here -->

			</ul>
		</div>

		<div  data-role="footer">
			<h1>Made by VTT & mFabrik.</h1>
		</div>
	</div>

	<!-- Start of second page -->
	<div data-role="page" id="programs_page">

		<div data-role="header" id="channel-header">
			<h1>Channel name here</h1>
		</div><!-- /header -->

		<div  data-role="content">
			<ul data-role="listview" data-inset="true" id="programs_list" data-split-icon="star">
				<li data-role="list-divider">Programs</li>
				<!-- Generated programs list here -->
			</ul>
		</div>

		<div data-role="footer">
			<h4>Made by VTT & mFabrik.</h4>
		</div><!-- /header -->
	</div><!-- /page -->

</body>

</html>

